package com.pybox.service;

import com.pybox.common.utils.JdbcTemplateUtils;
import com.pybox.dto.*;
import com.pybox.entity.TGroups;
import com.pybox.entity.TWeekTime;
import com.pybox.oauth.conf.UserDto;
import com.pybox.repository.TGroupsRepository;
import com.pybox.repository.TUserGroupObjectsRepository;
import com.pybox.repository.TWeekTimeRepository;
import com.pybox.spec.TGroupsSpec;
import com.pybox.util.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 描述：TGroups Service
 *
 * @author wuyingkai
 * @date 2018-09-15
 */

@Service
@Slf4j
@Transactional
public class TGroupsService {

    @Autowired
    private TGroupsRepository repository;

    @Autowired
    private TWeekTimeRepository weekTimeRepository;

    @Autowired
    private TUserGroupObjectsRepository tUserGroupObjectsRepository;

    @Autowired
    private TWeekTimeService tWeekTimeService;

    /**
     * 创建TGroups
     *
     * @param source
     * @return
     */
    public boolean create(TGroupsDto source) {

        TGroups target = new TGroups();
        BeanUtils.copyProperties(source, target);
        Integer customerId = UserUtils.getCustomerId();
        target.setCustomerId(customerId);
        target.setCtime(new Timestamp(System.currentTimeMillis()));
        target.setDeleted(0);
        UserDto user =UserUtils.getCurrentUser();
        if (user.getCustomerId() != null && user.getCustomerId() >0){
            target.setCustomerId(user.getCustomerId());
        }
        if (user.getId() != 0){
            target.setCreateby(user.getId());
        }
        repository.save(target);
        //保存分组的weektime

        for (TWeekTimeDto td : source.getWeekTimeDtos()) {
            td.setGroupId(target.getId());
            tWeekTimeService.create(td);
        }
        return true;

    }

    /**
     * 根据ID删除TGroups
     *
     * @param id
     * @return
     */
    public boolean delete(Integer id) {
        TGroups exist = repository.findOne(id);
        exist.setDeleted(1);
        repository.save(exist);
        return true;

    }

    /**
     * 更新TGroups
     *
     * @param id
     * @param source
     * @return
     */
    public boolean update(Integer id, TGroupsDto source) {

        TGroups exist = repository.findOne(id);
        if (null == exist) {
            throw new RuntimeException("记录不存在");
        }
        UserDto user =UserUtils.getCurrentUser();
        BeanUtils.copyProperties(source, exist, new String[]{"id"});
        exist.setUtime(new Timestamp(System.currentTimeMillis()));
        exist.setDeleted(0);
        if (user.getId() !=0){
            exist.setUpdateby(user.getId());
        }
        repository.save(exist);
        //再删除Tweektime
        weekTimeRepository.deleteByGroupId(exist.getId());
        //保存一次TweekTime
        for (TWeekTimeDto td : source.getWeekTimeDtos()) {
            td.setGroupId(exist.getId());
            tWeekTimeService.create(td);
        }
        return true;

    }

    /**
     * 根据ID查询TGroups
     *
     * @param id
     * @return
     */
    public TGroupsDto detail(Integer id) {

        TGroups exist = repository.findOne(id);
        if (null == exist) {
            throw new RuntimeException("记录不存在");
        }
        List<TWeekTime> weekTime = weekTimeRepository.findAllByGroupId(exist.getId());
        List<TWeekTimeDto> WeekTimeDtoList = new ArrayList<TWeekTimeDto>();
        for (TWeekTime td : weekTime) {
            TWeekTimeDto source = new TWeekTimeDto();
            List<Integer> integerList = new ArrayList<>();
            source.setDayofweek(td.getDayofweek());
            source.setGroupId(exist.getId());
            for (int i = 0; i < 24; i++) {
                try {
                    Method m = td.getClass().getDeclaredMethod("getHour" + i);
                    Object obj = m.invoke(td);
                    if (null != obj) {
                        integerList.add((Integer) obj);
                    }
                } catch (Exception e) {
                    log.error("method not exist");
                }
            }
            source.setHours(integerList);
            WeekTimeDtoList.add(source);
        }
        TGroupsDto target = new TGroupsDto();
        target.setWeekTimeDtos(WeekTimeDtoList);
        BeanUtils.copyProperties(exist, target);

        return target;

    }

    /**
     * 分页查询查询TGroups
     *
     * @param pageNo
     * @param pageSize
     * @param paramMap
     * @return
     */
    public Page<TGroupsDto> page(Integer pageNo, Integer pageSize, Map<String, String> paramMap) {

        Pageable pageable = new PageRequest(pageNo - 1, pageSize);

        //默认只能看自己一个公司的
        Integer customerId = UserUtils.getCustomerId();
        Integer isAdmin = UserUtils.getCurrentUser().getIsAdmin();
        if ((isAdmin ==0 || isAdmin ==1 ||isAdmin == 2) &&  customerId !=null && customerId >0){
            paramMap.put("customerId",customerId.toString());
        }
        Page<TGroups> data = repository.findAll(new TGroupsSpec(paramMap), pageable);

        List<TGroupsDto> list = new ArrayList<>();
        for (TGroups obj : data.getContent()) {
            TGroupsDto dto = new TGroupsDto();
            BeanUtils.copyProperties(obj, dto);
            list.add(dto);
        }

        Page<TGroupsDto> page = new PageImpl<>(list, pageable, data.getTotalElements());

        return page;

    }


    /**
     * 一个组关联多个人
     * @param dto
     * @return
     */
    public Result<Boolean> updateUsersByGroupId(GroupUsersDto dto) {
        //先删除再插入记录
        tUserGroupObjectsRepository.deleteByGroupId(dto.getGroupId());
        for (Integer userId:dto.getUserIds()){
            tUserGroupObjectsRepository.addUserIdsByGroupId(dto.getGroupId(),userId);
            }
        return Result.ok(true);
    }

    public Result<Boolean> updateObjectsByGroupId(GroupObjectsDto dto){
        //更新关联为空
        tUserGroupObjectsRepository.deleteObjectIdByGroupId(dto.getGroupId());
        for (Integer objectId:dto.getObjectIds()){
            tUserGroupObjectsRepository.addObjectIdsByGroupId(dto.getGroupId(),objectId);
        }
     return  Result.ok(true);
    }

    public Result<GroupObjectsDto> getObjectsByGroupId (Integer groupId){
        List<Integer> objectsIds = tUserGroupObjectsRepository.getObjectIdsByGroupId(groupId);
        List<Integer> otherObjectIds =tUserGroupObjectsRepository.getOtherObjectIdsByGroupId(groupId);
        GroupObjectsDto dto = new GroupObjectsDto();
        dto.setGroupId(groupId);
        dto.setObjectIds(objectsIds);
        dto.setOtherObjectIds(otherObjectIds);
        return Result.ok(dto);
    }
    public Result<GroupUsersDto> getUsersByGroupId (Integer groupId){
        List<Integer> userIds = tUserGroupObjectsRepository.getUserIdsByGroupId(groupId);
        List<Integer> otherUserIDs =tUserGroupObjectsRepository.getOtherUserIdsByGroupId(groupId);
        GroupUsersDto dto = new GroupUsersDto();
        dto.setGroupId(groupId);
        dto.setUserIds(userIds);
        dto.setOtherUserIDs(otherUserIDs);
        return Result.ok(dto);
    }

}
